package com.yingjia.yingjiauniversity.retrofit.convert;


import com.yingjia.yingjiauniversity.json.manager.JsonManager;
import com.yingjia.yingjiauniversity.retrofit.IConvert;
import com.yingjia.yingjiauniversity.utils.GenericReflectUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by 张智轶 on 2016/10/13.
 */
public abstract class ResponseBodyConvertSupport<T, V> implements IConvert<T, V>, Converter<ResponseBody, V> {
    private Type tempType;
    private Type destType;
    protected Logger logger = LoggerFactory.getLogger(((Object) this).getClass());

    public ResponseBodyConvertSupport() {
        Type[] superclassTypeParameter = GenericReflectUtil.getSuperclassTypeParameter(this.getClass());
        if (superclassTypeParameter != null) {
            if (superclassTypeParameter[0] != null) {
                tempType = superclassTypeParameter[0];
            }
            if (superclassTypeParameter[1] != null) {
                destType = superclassTypeParameter[1];
            }
        }
    }

    @Override
    public V convert(ResponseBody value) throws IOException {
        String jsonString = value.string();
        logger.info("ResponseBodyConvertSupport: json String=" + jsonString);
        T temp = JsonManager.getInstance().getComponent().toObject(jsonString, tempType, null);
        V dest = convertBean(temp);
        return dest;
    }


}
